package com.heart.common.utils;

import com.heart.common.constant.AppConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class CookieUtils {

    private static Logger logger = LoggerFactory.getLogger(CookieUtils.class);
    /**
     * 设置cookie
     * @param response
     * @param name
     * @param value
     */
    public static void setCookie(HttpServletResponse response,String name,String value,int maxAge)  {
        Cookie cookie = null;
        try {
            cookie = new Cookie(name, URLEncoder.encode(value, AppConstant.UTF8));
        } catch (UnsupportedEncodingException e) {
            logger.error("Cookie设置失败！",e);
        }
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 获取所有的cookie
     * @param request
     * @return
     */
    public static Map<String,String> getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        Map<String,String> result = new HashMap<>();
        for(Cookie cookie: cookies) {
            try {
                result.put(cookie.getName(),URLEncoder.encode(cookie.getValue(),AppConstant.UTF8));
            } catch (UnsupportedEncodingException e) {
                logger.error("Cookie获取失败！",e);
            }
        }
        return result;
    }
}
